﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RonYee.Models;
using RonYee.Service;

namespace RonYee.Controllers
{
    public class OrderController : Controller
    {
        RongeDb db = new RongeDb();
        //
        // GET: /Order/
        #region  //查阅图书订单

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult OrdersOfPending()
        {
            //检索待处理的订单，状态status=0
            var order = from o in db.Orders
                        where o.Status == 0
                        select o;
            int Status = 0;

            foreach (var item in order)
            {
                Status = item.Status;
            }

            ViewBag.status = Status;
            ViewBag.Error = "";
            return View(order);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult OrdersHasApproved()
        {
            //检索同意的订单，状态status=1
            var order = from o in db.Orders
                        where o.Status == 1
                        select o;
            int Status = 0;

            foreach (var item in order)
            {
                Status = item.Status;
            }

            ViewBag.status = Status;
            ViewBag.Error = "";
            return View(order);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult OrdersHasRejected()
        {
            //检索拒绝的订单，状态status=2
            var order = from o in db.Orders
                        where o.Status == 2
                        select o;
            int Status = 0;

            foreach (var item in order)
            {
                Status = item.Status;
            }

            ViewBag.status = Status;
            return View(order);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult OrdersHasClosed()
        {
            //检索关闭的订单，状态status=3
            var order = from o in db.Orders
                        where o.Status == 3
                        select o;
            int Status = 0;

            foreach (var item in order)
            {
                Status = item.Status;
            }

            ViewBag.status = Status;
            return View(order);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult OrdersHasRevoked()
        {
            //检索撤销的订单，状态status=4
            var order = from o in db.Orders
                        where o.Status == 4
                        select o;
            int Status = 0;

            foreach (var item in order) 
            {
                Status = item.Status;
            }

            ViewBag.status = Status;
            return View(order);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Details(int id) 
        {
            var details = from d in db.OrderDetails
                          where d.OrderId == id
                          select d;
            var order = (from o in db.Orders
                         where o.OrderId == id
                         select o).FirstOrDefault();

            int n = (from o in db.Orders
                         where o.OrderId == id
                          select o.Status).FirstOrDefault();

            ViewBag.status = n;
            ViewBag.Error = "";
            ViewData["details"] = details;

            return View(order);
        }

        public ActionResult ToCloseOrder(int id) 
        {
            var details = from d in db.OrderDetails
                          where d.OrderId == id
                          select d;
            var order = (from o in db.Orders
                         where o.OrderId == id
                         select o).FirstOrDefault();

            int n = (from o in db.Orders
                     where o.OrderId == id
                     select o.Status).FirstOrDefault();

            ViewBag.status = n;
            ViewBag.Error = "如果有财务支出，请填写财务费用！";
            ViewData["details"] = details;

            return View(order);
        }

        #endregion

        #region  //处理图书订单

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Index()
        {
            RonYee.Models.MvcPage Model = new MvcPage();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Order> datesource = GetDataSource();//要分页的数据源
            Model.OrderList = datesource.Where(r => r.OrderId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.OrderList = datesource.Where(r => r.OrderId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Order> GetDataSource()
        {
            var order = from b in db.Orders
                          orderby b.OrderDate ascending
                          select b;
            List<Order> model = new List<Order>();
            foreach (var item in order)
            {
                model.Add(item);
            }
            return model;
        }

        public ActionResult PageIndex(RonYee.Models.MvcPage Model)
        {

            //分页数据源。自己写逻辑获取。


            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Order> datesource = GetDataSource();//要分页的数据源
            Model.OrderList = datesource.Where(r => r.OrderId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("Index", Model);
            }
            //return View(Model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Search()
        {
            int id = 0;
            if (Request.Form["s_id"] != "")
            {
                id = Convert.ToInt32(Request.Form["s_id"]);
            }
            string name = Request.Form["s_name"];
            string sno = Request.Form["s_no"];
            DateTime start = Convert.ToDateTime("2010-1-1");
            if (Request.Form["s_time"] != "") 
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (id > 0)
            {

                var order = from o in db.Orders
                            where o.OrderId == id
                            select o;

                int n = (from o in db.Orders
                         where o.OrderId == id
                         select o).Count();
                ViewBag.Count = n;
                return View(order);
            }
            else if (name != "" && sno != "")
            {
                var order = from b in db.Orders
                            where b.Username == name && b.UserNo.Contains(sno) && b.OrderDate >= start
                            orderby b.OrderDate ascending
                            select b;
                int n = (from b in db.Orders
                         where b.Username == name && b.UserNo.Contains(sno) && b.OrderDate >= start
                         orderby b.OrderDate ascending
                         select b).Count();
                ViewBag.Count = n;
                return View(order);
            }
            else if (name != "" && sno == "")
            {
                var order = from b in db.Orders
                            where b.Username.Contains(name) && b.OrderDate >= start
                            orderby b.OrderDate ascending
                            select b;
                int n = (from b in db.Orders
                         where b.Username.Contains(name) && b.OrderDate >= start
                         orderby b.OrderDate ascending
                         select b).Count();
                ViewBag.Count = n;
                return View(order);
            }
            else if (name == "" && sno != "")
            {
                var order = from b in db.Orders
                            where b.UserNo.Contains(sno) && b.OrderDate >= start
                            orderby b.OrderDate ascending
                            select b;
                int n = (from b in db.Orders
                         where b.UserNo.Contains(sno) && b.OrderDate >= start
                         orderby b.OrderDate ascending
                         select b).Count();
                ViewBag.Count = n;
                return View(order);
            }
            else
            {
                return RedirectToAction("Index");
            }

        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult ApprovedTheOrder(int id) 
        {
            var List = (from n in db.OrderDetails
                           where n.OrderId == id
                           select n).FirstOrDefault();

            //先改变订单的状态为1
            if (ChangeTheOrderStatus(id, 1))
            {
                //订单修改成功
                string isbn = List.ISBN;
                int count = List.Quantity;

                //修改图书的库存数
                ReduceCountInBooks(isbn, count);
                return RedirectToAction("OrdersOfPending");
            }
            else
            {
                //返回订单修改失败信息
                ViewBag.Error = "订单操作失败！";
                return RedirectToAction("OrdersOfPending");
            }
            
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult RevokedTheOrder(int id)
        {
            var List = (from n in db.OrderDetails
                        where n.OrderId == id
                        select n).FirstOrDefault();

            //先改变订单的状态为2
            if (ChangeTheOrderStatus(id, 2))
            {
                //订单修改成功
                string isbn = List.ISBN;
                int count = List.Quantity;

                //修改图书的库存数
                IncreaseCountInBooks(isbn, count);
                return RedirectToAction("OrdersHasApproved");
            }
            else
            {
                //返回订单修改失败信息
                ViewBag.Error="订单操作失败！";
                return RedirectToAction("OrdersHasApproved");
            }

        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult ClosedTheOrder()
        {
            string orderId = Request.Form["OrderId"];
            int id = Convert.ToInt32(orderId);
            decimal cost = 0;
            if (Request.Form["Finance"] != "")
            {
                cost = Convert.ToDecimal(Request.Form["Finance"]);
            }
            var order = db.Orders.Find(id);
            //先改变订单的状态为3
            if (ChangeTheOrderStatus(id, 3))
            {
                //订单修改成功
                //进行数据更新操作，删除书库的条目，更改图书的count
                //UpdateTheDataInBooksAndInStores(id);

                var List = from n in db.OrderDetails
                           where n.OrderId == id
                           select n;
                if (List != null)
                {
                    try
                    {
                        foreach (var item in List)
                        {
                            int bookId = item.BookId;
                            string isbn = item.ISBN;
                            int count = item.Quantity;

                            for (int i = 0; i < count; i++)
                            {
                                //DeleteItemsInStores(isbn);

                                var book = (from b in db.InStores
                                            where b.ISBN == isbn
                                            orderby b.InStoreId ascending
                                            select b).FirstOrDefault();
                                db.InStores.Remove(book);

                            }
                        }
                        db.SaveChanges();
                    }
                    catch (FieldAccessException ex)
                    {
                        ViewBag.Error = ex.Message;
                    }
                }
                
                //写入财务报表记录
                Financial f1 = new Financial();
                f1.OrderId = orderId;
                f1.Editor = HttpContext.User.Identity.Name;
                f1.AddTime = DateTime.Now;
                f1.Total = order.Total;
                f1.FinancialCost = cost;
                db.Financials.Add(f1);
                db.SaveChanges();
                ViewBag.Error = "订单操作成功！";
                return RedirectToAction("OrdersHasApproved");
            }
            else
            {
                //返回订单修改失败信息
                ViewBag.Error = "订单操作失败！";
                return RedirectToAction("OrdersHasApproved");
            }

        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult RejectedTheOrder(int id) 
        {
            //改变订单的状态为4
            if (ChangeTheOrderStatus(id, 4))
            {
                //订单修改成功
                return RedirectToAction("OrdersOfPending");
            }
            else
            {
                //返回订单修改失败信息
                return ViewBag.Error = "订单操作失败！";
            }

        }

        //更改订单的状态
        public bool ChangeTheOrderStatus(int id,int status)
        {
            var order = db.Orders.Find(id);
            if (order != null)
            {
                order.Status = status;
                UpdateModel(order);
                db.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }

        public void UpdateTheDataInBooksAndInStores(int id)
        {
            var List = from n in db.OrderDetails
                           where n.OrderId == id
                           select n;
            if (List != null)
            {
                try
                {
                    foreach (var item in List)
                    {
                        int bookId = item.BookId;
                        string isbn = item.ISBN;
                        int count = item.Quantity;

                        for (int i = 0; i < count; i++)
                        {
                            //DeleteItemsInStores(isbn);

                            var book = (from b in db.InStores
                                        where b.ISBN == isbn
                                        orderby b.InStoreId ascending
                                        select b).FirstOrDefault();
                            db.InStores.Remove(book);
                            
                        }
                    }
                    db.SaveChanges();
                }
                catch( FieldAccessException ex)
                {
                    ViewBag.Error= ex.Message;
                }
            }

        }

        //对Instores表进行图书出库删除操作
        public void DeleteItemsInStores(string isbn) 
        {
            var item = (from b in db.InStores
                        where b.ISBN == isbn
                        orderby b.InStoreId ascending
                        select b).FirstOrDefault();
            try
            {
                db.InStores.Remove(item);
                db.SaveChanges();
            }
            catch (FieldAccessException ex) 
            {
                ViewBag.Error = ex.Message;
            }
        }

        //在books表中修改Count数
        public void UpdateInBooks(string isbn)
        {
            try
            {
                int count = GetBooksInfo.GetBooksCount(isbn);
                int id = GetBooksInfo.GetBooksID(isbn);
                var b = db.Books.Find(id);
                if (b != null)
                {
                    b.BookCount = count;
                    UpdateModel(b);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
            }

        }
        //在books表中修改Count数
        public void ReduceCountInBooks(string isbn, int count)
        {
            try
            {
                int id = GetBooksInfo.GetBooksID(isbn);
                var b = db.Books.Find(id);
                if (b != null)
                {
                    b.BookCount = b.BookCount - count;
                    UpdateModel(b);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
            }

        }

        public void IncreaseCountInBooks(string isbn, int count)
        {
            try
            {
                int id = GetBooksInfo.GetBooksID(isbn);
                var b = db.Books.Find(id);
                if (b != null)
                {
                    b.BookCount = b.BookCount + count;
                    UpdateModel(b);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
            }

        }

        #endregion

        #region  //个人订单查看

        [Authorize]
        public ActionResult PersonalOrders() 
        {
            string name = HttpContext.User.Identity.Name;
            var order = from o in db.Orders
                        where o.Username == name
                        orderby o.OrderDate descending
                        select o;
            return View(order);
        }

        [Authorize]
        public ActionResult OrdersDetails(int id)
        {
            var details = from d in db.OrderDetails
                          where d.OrderId == id
                          select d;
            var order = (from o in db.Orders
                         where o.OrderId == id
                         select o).FirstOrDefault();

            int n = (from o in db.Orders
                     where o.OrderId == id
                     select o.Status).FirstOrDefault();

            ViewBag.status = n;
            ViewBag.Error = "";
            ViewData["details"] = details;

            return View(order);
        }

        #endregion

        #region   //订单提交



        #endregion


    }
}
